package org.ash.user.config;

import lombok.extern.slf4j.Slf4j;
import org.ash.base.exception.AdBaseException;
import org.ash.base.model.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException ex) {
        log.info("全局异常处理：{}",ex.getMessage());
        // 提取校验错误信息
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.joining("; "));
        return Result.error(errorMessage);
    }

    @ResponseBody
    @ExceptionHandler(AdBaseException.class)
    public Result customException(AdBaseException e) {

        // 记录异常
        log.error("全局异常处理：{}", e.getErrMessage());

        // 解析出异常信息
        String errMessage = e.getErrMessage();
        return Result.error(errMessage);
    }
}
